package cn.easybuy.servlet.Cart;

import cn.easybuy.entity.BuyCar;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

@WebServlet("/buyCarNumServlet")
public class BuyCarNumServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取id ，数量
        String entityId = req.getParameter("entityId");
        String quantity = req.getParameter("quantity");
        HttpSession session = req.getSession();
        List<BuyCar> list = (List<BuyCar> )session.getAttribute("listCarSession");
        float total=0;//总计
        float sum=0;//小计
        for (BuyCar buyCar : list) {
            if(buyCar.getId()==Integer.parseInt(entityId)){
                int count =Integer.parseInt(quantity);
                buyCar.setNum(count);
                buyCar.setSum(buyCar.getPrice(),count);
                sum=buyCar.getSum();
            }
            total+=buyCar.getSum();
        }
        session.setAttribute("sum",total);
        HashMap<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("sum",sum);
        String jsonstr = JSONObject.toJSONString(map);

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        pw.print(jsonstr);
        pw.flush();
        pw.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
